import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class StartButton extends StatefulWidget {
  const StartButton({
    super.key,
    this.width = 320,
    this.height = 70,
    this.title = "让我们开始练习",
    this.onPressed,
  });

  final double width;
  final double height;
  final String title;
  final VoidCallback? onPressed;

  @override
  State<StartButton> createState() => _StartButtonState();
}

class _StartButtonState extends State<StartButton> with RouteAware {
  final RouteObserver<PageRoute> _routeObserver = RouteObserver<PageRoute>();
  bool _disabled = true; // 状态移动到State中

  Future<void> _changeStatus() async {
    final prefs = await SharedPreferences.getInstance();
    final hasSelectedBook = prefs.getString("selectBook") != null;

    if (mounted) {
      setState(() {
        _disabled = !hasSelectedBook; // 使用正确状态判断
      });
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context);
    if (route is PageRoute) {
      _routeObserver.subscribe(this, route);
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) => _changeStatus());
  }

  @override
  void dispose() {
    _routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPopNext() {
    if (mounted) _changeStatus();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return SizedBox(
      height: widget.height,
      width: widget.width,
      child: FloatingActionButton(
        onPressed: _disabled ? null : widget.onPressed,
        backgroundColor: _disabled
            ? theme.colorScheme.primary.withValues(alpha: 0.5) // 修复透明度设置
            : theme.colorScheme.primary,
        foregroundColor: theme.colorScheme.onSecondary,
        child: Text(
          _disabled ? "🚧请在选择词书后继续🚧" : widget.title,
          style: const TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
    );
  }
}